import java.util.*;


  class ListNode {
   int val;
   ListNode next = null;
   public ListNode(int val) {
     this.val = val;
   }
 }

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public static ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        ListNode dum = new ListNode(0);
        ListNode cur = dum;
        head1 = reverse(head1);
        head2 = reverse(head2);
        int flg = 0;
        while(head1 != null && head2 != null) {
           int sum = (head1.val + head2.val + flg)%10;
            cur.next = new ListNode(sum);
            flg = (head1.val + head2.val + flg)/10;
            cur = cur.next;
            head1 = head1.next;
            head2 = head2.next;
        } 
         while(head1 != null) {
            int sum = (head1.val + flg)%10;
            cur.next = new ListNode(sum);
            flg = (head1.val + flg)/10;
            cur = cur.next;
            head1 = head1.next;
        } 
         while(head2 != null) {
            int sum = (head2.val + flg)%10;
            cur.next = new ListNode(sum);
            flg = (head2.val + flg)/10;
            cur = cur.next;
            head2 = head2.next;
        } 
        while(flg != 0) {
            
            cur.next = new ListNode(flg%10);
            flg /= 10;
            cur = cur.next;
        }
        return reverse(dum.next);
    }
    public static ListNode reverse(ListNode head) {
        ListNode pre = null;
        while(head != null) {
            ListNode Next = head.next;
            head.next = pre;
            pre = head;
            head = Next;
            
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode head1 = new ListNode(9);
        head1.next = new ListNode(3);
        head1.next.next = new ListNode(7);
        ListNode head2 = new ListNode(6);
        head2.next = new ListNode(3);
        addInList(head1,head2);
    }
}